//
//  ShellRegisteredViewController.m
//  ShellWallert
//
//  Created by lvzhao on 2019/10/1.
//  Copyright © 2019 VV. All rights reserved.
//

#import "ShellRegisteredViewController.h"
#import "ShellAccountTextField.h"
#import "ShellLanguageViewController.h"
#import "ShellAccountViewModel.h"
#import "ShellSelectCountryViewController.h"



@interface ShellRegisteredViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) UIButton *verificationBtn;

//取消订阅RAC信号
@property (nonatomic,strong) RACDisposable *disposable;
@property (nonatomic,assign) NSInteger timeCount;

@property (nonatomic,strong) ShellAccountViewModel *viewModel;

@end



@implementation ShellRegisteredViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = LZLocalizedString(@"注册");
    
    [self setupView];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //查看堆栈, 看是否有该VC
    NSArray * navs = self.navigationController.viewControllers;
    BOOL isDispose = YES;
    for (UIViewController * vc in navs){
        NSString * VCString =  NSStringFromClass([vc class]);
        NSString * orderVCString =  NSStringFromClass([self class]);
        if([VCString isEqualToString:orderVCString]){
            isDispose = NO;
        }
    }
    if(isDispose) {
        //释放定时器
        [self.disposable dispose];
        self.disposable = nil;
    }
}


- (void)setupView{
    
    ///!!!:切换语言
    //获取本地语言
    UIButton *languageBtn = [UIButton lz_buttonTitle:kShellLanguageManager.language titleColor:UIColorHex(0x8D99B2) fontSize:14];
    languageBtn.frame = CGRectMake(0, 0, 100, 20);
    languageBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [languageBtn setImage:k_imageName(@"icon_language") forState:UIControlStateNormal];
    [languageBtn SG_imagePositionStyle:SGImagePositionStyleRight spacing:9];
    [self initBarItem:languageBtn withType:1];
    
    
    ///!!!:logo
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = k_imageName(@"icon_logo");
     [self.view addSubview:imageView];
     [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.mas_equalTo(54);
         make.centerX.mas_equalTo(self.view.mas_centerX);
         make.width.mas_equalTo(70);
         make.height.mas_equalTo(100);
     }];
    
    ///!!!:邮箱
    ShellAccountTextField *accountTextField = [[ShellAccountTextField alloc] init];
    accountTextField.tag = 2019;
    accountTextField.keyboardType = UIKeyboardTypeEmailAddress;
    accountTextField.placeholder = LZLocalizedString(@"邮箱");
    [self.view addSubview:accountTextField];
    [accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(imageView.mas_bottom).mas_offset(50);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
    }];
    
    
    ///!!!:邮箱验证码
    ShellAccountTextField *codeTextField = [[ShellAccountTextField alloc] init];
    codeTextField.placeholder = LZLocalizedString(@"邮箱验证码");
    codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:codeTextField];
    [codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(accountTextField.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
    }];
    

    self.verificationBtn.frame = CGRectMake(0, 0, 110, 50);
    codeTextField.rightView = self.verificationBtn;
    codeTextField.rightViewMode = UITextFieldViewModeAlways;
    
    
    
    
    ///!!!:选择国家
    ShellAccountTextField *countryTextField = [[ShellAccountTextField alloc] init];
    countryTextField.delegate = self;
    countryTextField.text = @"中国";
    countryTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:countryTextField];
    [countryTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(codeTextField.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
    }];
    
    UIButton *selectCountryBtn = [UIButton lz_buttonImageName:@"ico_next_xiaojiantou" backgroundImageName:@""];
    selectCountryBtn.frame = CGRectMake(0, 0, 50, 50);
    countryTextField.rightView = selectCountryBtn;
    countryTextField.rightViewMode = UITextFieldViewModeAlways;

    
    ///!!!:密码
    ShellAccountTextField *passwordTextField = [[ShellAccountTextField alloc] init];
    passwordTextField.secureTextEntry = YES;
    passwordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    [self.view addSubview:passwordTextField];
    passwordTextField.placeholder = LZLocalizedString(@"密码");
    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(countryTextField.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
    }];
    
    
    ///!!!:邀请码
    ShellAccountTextField *invitationTextField = [[ShellAccountTextField alloc] init];
    [self.view addSubview:invitationTextField];
    invitationTextField.placeholder = LZLocalizedString(@"邀请码(非必须)");
    invitationTextField.keyboardType = UIKeyboardTypeASCIICapable;
    [invitationTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(passwordTextField.mas_bottom).mas_offset(20);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
    }];
    
    
    
    ///!!!:注册
    UIButton *registeredBtn = [UIButton lz_buttonTitle:LZLocalizedString(@"注册") titleColor:UIColorHex(0xFFFFFF) fontSize:17];
    [registeredBtn setGradientBackgroundWithColors:@[UIColorHex(0x65DFFE),UIColorHex(0x2C6FE)] locations:@[@(0), @(1.0f)] startPoint:CGPointMake(1, 0.5) endPoint:CGPointMake(0, 0.5)];
    [self.view addSubview:registeredBtn];
    registeredBtn.cornerRadius = 6;
    registeredBtn.layer.shadowOffset = CGSizeMake(0,2);
    registeredBtn.layer.shadowOpacity = 1;
    registeredBtn.layer.shadowRadius = 6;
    registeredBtn.enabled = NO;
    [registeredBtn setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateDisabled];
    [registeredBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(invitationTextField.mas_bottom).mas_offset(26);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
    }];
    
    
    
    
    ///!!!:去登录
    UIButton *loginBtn = [UIButton lz_buttonTitle:LZLocalizedString(@"已有账号,直接登录") titleColor:UIColorHex(0x8D99B2) fontSize:17];
    loginBtn.backgroundColor = UIColorHex(0x0D3354);
    [self.view addSubview:loginBtn];
    loginBtn.cornerRadius = 6;
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(registeredBtn.mas_bottom).mas_offset(30);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(50);
    }];
    
    //注册按钮的控制
    [[accountTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        if(accountTextField.text.length > 6
           && passwordTextField.text.length >5
           && codeTextField.text.length > 3){
            registeredBtn.enabled = YES;
        } else {
            registeredBtn.enabled = NO;
        }
    }];
    
    
    [[passwordTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        if(accountTextField.text.length > 6
           && passwordTextField.text.length >5
           && codeTextField.text.length > 3){
            registeredBtn.enabled = YES;
        } else {
            registeredBtn.enabled = NO;
        }
    }];
    

    [[codeTextField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        if(accountTextField.text.length > 6
           && passwordTextField.text.length >5
           && codeTextField.text.length > 3){
            registeredBtn.enabled = YES;
        } else {
            registeredBtn.enabled = NO;
        }
    }];
    
    
    @weakify(self);
    [[loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        ///!!!:去登录
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [[registeredBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        ///!!!:去注册  请求网络
        
        @strongify(self);
        [self.view endEditing:YES];
        [self.viewModel registerAccount:accountTextField.text areaCode:countryTextField.text invitCode:invitationTextField.text verification:codeTextField.text password:passwordTextField.text];
    }];

    
    ///选择国家
    [[selectCountryBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        @strongify(self);
        [self.view endEditing:YES];
        RACSubject *countrySubJect = [RACSubject subject];

        ShellSelectCountryViewController *countryVC = [[ShellSelectCountryViewController alloc] init];
        
        [self.navigationController pushViewController:countryVC animated:YES];
        countryVC.selectSubject = countrySubJect;
        [countrySubJect subscribeNext:^(id  _Nullable x) {
            ShellCountryModel *countryModel = x;
            countryTextField.text = countryModel.name;
        }];
    }];
    
    ///!!!:选择语言
    [[languageBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        ShellLanguageViewController *languageVC = [[ShellLanguageViewController alloc] init];
        [self.navigationController pushViewController:languageVC animated:YES];
        
    }];
    
    
    ///!!!:国际化
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:k_APPLanguageWillChangeNotificationName object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        self.title = LZLocalizedString(@"注册");
        [languageBtn setTitle:kShellLanguageManager.language forState:UIControlStateNormal];
        [languageBtn SG_imagePositionStyle:SGImagePositionStyleRight spacing:9];
        accountTextField.placeholder = LZLocalizedString(@"邮箱");
        codeTextField.placeholder = LZLocalizedString(@"邮箱验证码");
        passwordTextField.placeholder = LZLocalizedString(@"密码");
        invitationTextField.placeholder = LZLocalizedString(@"邀请码(非必须)");
        [registeredBtn setTitle:LZLocalizedString(@"注册") forState:UIControlStateNormal];
        [loginBtn setTitle:LZLocalizedString(@"已有账号,直接登录") forState:UIControlStateNormal];
        [self.verificationBtn setTitle:[NSString stringWithFormat:@"%@",LZLocalizedString(@"获取验证码")] forState:UIControlStateNormal];

    }];

    
    ///回调
    [self.viewModel.reloadSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self actionType:[x integerValue]];
    }];
    
    
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    if(data){
        NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         NSString *ipStr = nil;
         if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
             ipStr = ipDic[@"data"][@"ip"];
         }
         NSString *url = [NSString stringWithFormat:@"http://apis.juhe.cn/ip/ipNew?ip=%@&key=e2a0ddd8aa7463579a1d18da808868dc",ipStr];
         [LZNetworkingManager lz_request:@"get" url:url params:nil success:^(id  _Nullable responseObject) {
             
             if([responseObject[@"resultcode"] isEqualToString:@"200"]){
                 NSDictionary *resultDictionary = responseObject[@"result"];
                 NSString *country = resultDictionary[@"Country"];
                 countryTextField.text = country;
                 
             }
         } failure:^(NSError * _Nullable error) {
             
         }];
    }
 
    
    
    
}


///处理逻辑问题
- (void)actionType:(NSInteger)type{
    
    switch (type) {
        case 1:{
            [self startDisposable];
        }
            break;
        default:
            break;
    }
    
    
}


//发送验证码
- (void)verificationCodeClick:(UIButton *)btn{
    ShellAccountTextField *accountTextField = [self.view viewWithTag:2019];
    if(accountTextField.text.length == 0)return;
    [self.viewModel sendVerifiCode:accountTextField.text type:1];
}

//开启倒计时
- (void)startDisposable {
    
    @weakify(self)
    [self.view endEditing:YES];
    self.timeCount = K_timeCount;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.verificationBtn setTitle:[NSString stringWithFormat:@"%ldS",(long)self.timeCount] forState:self.timeCount > 0 ? UIControlStateDisabled:UIControlStateNormal];
    });
    
    self.verificationBtn.enabled = NO;
    
    //button type要 设置成custom 否则会闪动
    self.disposable = [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]]subscribeNext:^(NSDate * _Nullable x) {
        @strongify(self)
        //时间 --
        NSLog(@"发送验证码 %ld",(long)self.timeCount);
        
        self.timeCount -- ;
        if(self.timeCount < 1){
            self.verificationBtn.enabled = YES;
            self.timeCount  = 0;
            [self.disposable dispose];
            self.disposable = nil;
        } else {
            self.verificationBtn.enabled = NO;
        }
        //设置文字
        NSString * btnText = self.timeCount > 0 ? [NSString stringWithFormat:@"%ldS",(long)self.timeCount]:[NSString stringWithFormat:@"%@",LZLocalizedString(@"重新发送")];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self)
            [self.verificationBtn setTitle:btnText forState:self.timeCount > 0 ? UIControlStateDisabled:UIControlStateNormal];
            self.verificationBtn.frame = CGRectMake(0, 0, 110, 50);
        });
    }];
    
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}        // return NO to disallow editing.


- (UIButton *)verificationBtn{
    if(!_verificationBtn){
        _verificationBtn = [[UIButton alloc] init];
        [_verificationBtn setTitle:[NSString stringWithFormat:@"%@",LZLocalizedString(@"获取验证码")] forState:UIControlStateNormal];
        [_verificationBtn setTitleColor:UIColorHex(0x4AB2E7) forState:UIControlStateNormal];
        _verificationBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_verificationBtn addTarget:self action:@selector(verificationCodeClick:) forControlEvents:UIControlEventTouchUpInside];
        _verificationBtn.enabled = YES;
    }
    return _verificationBtn;
}



//viewModel;
- (ShellAccountViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ShellAccountViewModel alloc] init];
    }
    return _viewModel;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */







@end
